<template>
    <div>
      <!-- 面包屑导航区域 -->
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>分类参数</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 卡片视图区域 -->
      <el-card>
        <!-- 警告区域 -->
        <el-alert
          title="注意：只允许为第三级分类设置相关参数！"
          type="warning"
          :closable="false"
          show-icon>
        </el-alert>
        <!-- 选择商品分类区域 -->
        <el-row class="cat_opt">
          <el-col>
            <span>选择商品分类：</span>
            <!-- 选择商品分类的级联选择器 -->
            <el-cascader
              v-model="selectedCateId"
              :options="cateList"
              :props="{ expandTrigger: 'hover',children:'children',label: 'cat_name',value: 'cat_id' }"
              @change="handleChange">
            </el-cascader>
          </el-col>
        </el-row>
        <!-- tab页签区域 -->
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
          <!-- 添加动态参数面板 -->
          <el-tab-pane label="动态参数" name="many">
            <!-- 添加动态参数按钮 -->
            <el-button type="primary" size="mini" :disabled="isBtnDisabled"  @click="showAddCateDialog">添加参数</el-button>
            <!-- 动态参数表格 -->
            <el-table :data="manyTableData" border stripe>
              <!-- 展开行 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <!-- 循环渲染tag标签 -->
                  <el-tag
                    v-for="(value, index) in scope.row.attr_vals"
                    :key="index"
                    closable
                    @close="handleClose(index,scope.row)">
                    {{value}}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @blur="handleInputConfirm(scope.row)"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <!-- 索引列 -->
              <el-table-column type="index"></el-table-column>
              <el-table-column label="参数名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑参数</el-button>
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParam(scope.row.attr_id)">删除参数</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <!-- 添加静态属性面板 -->
          <el-tab-pane label="静态属性" name="only">
            <!-- 添加静态属性按钮 -->
            <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="showAddCateDialog">添加属性</el-button>
            <!-- 静态参数表格 -->
            <el-table :data="onlyTableData" border stripe>
              <!-- 展开行 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    v-for="(value, index) in scope.row.attr_vals"
                    :key="index"
                    closable
                    @close="handleClose(index,scope.row)">
                    {{value}}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <!-- 索引列 -->
              <el-table-column type="index"></el-table-column>
              <el-table-column label="参数名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑参数</el-button>
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParam(scope.row.attr_id)">删除参数</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 添加参数对话框 -->
      <el-dialog
        :title="'添加' + this.titleText"
        :visible.sync="addCateDialogVisible"
        width="30%"
        @close="addCateClose">
        <el-form :model="addCateForm" label-width="100px" :rules="addCateFormRules" ref="addCateFormRef">
          <el-form-item prop="attr_name" :label="this.titleText">
            <el-input v-model="addCateForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addCateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改参数对话框 -->
      <el-dialog
        :title="'修改' + this.titleText"
        :visible.sync="editCateDialogVisible"
        width="30%"
        @close="editCateClose">
        <el-form :model="editCateForm" label-width="100px" :rules="editCateFormRules" ref="editCateFormRef">
          <el-form-item prop="attr_name" :label="this.titleText">
            <el-input v-model="editCateForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editCateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
export default {
  data () {
    return {
      // 商品分类列表
      cateList: [],
      // 选中的商品分类的Id
      selectedCateId: [],
      // 被激活的页签的名称
      activeName: 'many',
      // 动态参数数据
      manyTableData: [],
      // 静态参数数据
      onlyTableData: [],
      // 控制添加参数对话框显示
      addCateDialogVisible: false,
      // 添加参数对话框表单绑定数据
      addCateForm: {
        attr_name: '',
        attr_sel: ''
      },
      // 添加参数对话框表单验证规则
      addCateFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 控制修改参数对话框显示
      editCateDialogVisible: false,
      // 修改参数对话框表单绑定数据
      editCateForm: {},
      // 添加参数对话框表单验证规则
      editCateFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 控制新增参数分支表单与按钮的切换显示
      inputVisible: false,
      // 新增参数分支表单绑定值
      inputValue: ''
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取分类列表失败')
      this.cateList = res.data
    },
    // 级联选择器发生变化时触发
    handleChange () {
      this.getParamsData()
    },
    // tab页签点击事件的处理函数
    handleTabClick () {
      this.getParamsData()
    },
    async getParamsData () {
      if (this.selectedCateId.length < 3) {
        this.selectedCateId = []
        this.manyTableData = []
        this.onlyTableData = []
        return 0
      }
      // 根据所处的页签请求数据
      const { data: res } = await this.$http.get('categories/' + this.cateId + '/attributes', {
        params: {
          sel: this.activeName
        }
      })
      if (res.meta.status !== 200) return this.$message.error('获取参数列表失败')
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制文本框的显示与隐藏
        item.inputVisible = false
        // 文本框绑定数据
        item.inputValue = ''
      })
      console.log(res.data)
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 监听按钮控制添加参数对话框显示
    showAddCateDialog () {
      this.addCateDialogVisible = true
    },
    // 添加参数对话框关闭，重置表单
    addCateClose () {
      this.$refs.addCateFormRef.resetFields()
    },
    // 发生请求添加参数
    addParams () {
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请正确输入参数名称')
        this.addCateForm.attr_sel = this.activeName
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, this.addCateForm)
        if (res.meta.status !== 201) return this.$message.error('添加参数失败')
        this.$message.success('添加参数成功')
        this.getParamsData()
        this.addCateDialogVisible = false
      })
    },
    // 发送请求修改参数
    editParams () {
      this.$refs.editCateFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请正确输入参数名称')
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editCateForm.attr_id}`, {
          attr_name: this.editCateForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error('修改参数失败')
        this.$message.success('修改参数成功')
        this.getParamsData()
        this.editCateDialogVisible = false
      })
    },
    // 监听修改参数对话框关闭,重置表单
    editCateClose () {
      this.$refs.editCateFormRef.resetFields()
    },
    // 监听修改参数按钮
    async showEditDialog (id) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, {
        params: {
          attr_sel: this.activeName
        }
      })
      if (res.meta.status !== 200) return this.$message.error('获取参数数据失败')
      this.editCateForm = res.data
      this.editCateDialogVisible = true
    },
    // 发生请求删除参数
    async deleteParam (id) {
      const res = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (res === 'confirm') {
        const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除参数失败!')
        this.$message.success('删除参数成功!')
        return this.getParamsData()
      } else {
        return this.$message.info('已取消删除!')
      }
    },
    // 点击新增属性分支按钮
    showInput (row) {
      row.inputVisible = true
      // 让文本框自动获取焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 新增属性分支失去焦点
    // $nextTick方法作用是当页面元素重新渲染后执行回调函数中的代码
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return 0
      }
      // 如果没有return则要进行后续处理
      row.attr_vals.push(row.inputValue)
      row.inputValue = ''
      row.inputVisible = false
      // 发生请求添加属性项
      const res = await this.setAttrvals(row)
      if (res.meta.status !== 200) return this.$message.error('添加失败！')
      this.$message.success('添加成功!')
    },
    // 删除标签
    async handleClose (index, row) {
      row.attr_vals = row.attr_vals.filter((val, i) => {
        return i !== index
      })
      // 发生请求删除属性项
      const res = await this.setAttrvals(row)
      if (res.meta.status !== 200) return this.$message.error('删除失败！')
      this.$message.success('删除成功!')
    },
    // 封装对attr_vals的操作封装
    async setAttrvals (row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      return res
    }
  },
  computed: {
    // 如果选中的为三级分类则取消禁用
    isBtnDisabled () {
      if (this.selectedCateId.length === 3) {
        return false
      } else {
        return true
      }
    },
    // 当前选中的分类id
    cateId () {
      if (this.selectedCateId.length === 3) {
        return this.selectedCateId[2]
      }
      return null
    },
    // 动态显示添加参数对话框标题
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-cascader {
  width: 250px;
}
.el-tag {
  margin: 10px;
}
.el-tag + .el-tag {
    margin-left: 10px;
}
.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}
.input-new-tag {
  width: 120px;
  margin-left: 10px;
}
</style>
